<template>
  <div class="app-container">
    <el-form ref="form" :model="form" :rules="rules" label-width="86px">
      <span style="font-size: 18px;">基础信息</span>
      <el-divider></el-divider>
      <el-row>
        <el-col :span="8">
          <el-form-item label="节目名称" prop="courseTitle">
            <el-input v-model="form.courseTitle" placeholder="请输入节目名称" />
          </el-form-item>
        </el-col>
        <!-- <el-col :span="8">
          <el-form-item label="课程等级" prop="level">
            <el-select v-model="form.level" placeholder="请选择课程等级" style="width: 100%">
              <el-option
                v-for="dict in levelOptions"
                :key="dict.dictValue"
                :label="dict.dictLabel"
                :value="dict.dictValue"
              ></el-option>
            </el-select>
          </el-form-item>
        </el-col>
        <el-col :span="8">
          <el-form-item label="课程时长" prop="courseLength">
            <el-input v-model="form.courseLength" placeholder="请输入课程时长" />
          </el-form-item>
        </el-col> -->
        <el-col :span="8">
          <el-form-item label="浏览人数" prop="viewNum">
            <el-input v-model="form.viewNum" placeholder="请输入浏览人数" />
          </el-form-item>
        </el-col>
        <el-col :span="8">
          <el-form-item label="点赞人数" prop="likeNum">
            <el-input v-model="form.likeNum" placeholder="请输入点赞人数" />
          </el-form-item>
        </el-col>
        <el-col :span="8">
          <el-form-item label="节目简图" prop="courseThumbUrl">
            <!-- <el-input v-model="form.courseThumbUrl" placeholder="请输入课程缩略图路径" /> -->
            <el-upload
              class="avatar-uploader"
              :action="uploadImgUrl"
              :headers="headers"
              :show-file-list="false"
              :on-success="handleUploadSuccess"
              :before-upload="beforeUpload"
            >
              <img v-if="form.courseThumbUrl" :src="form.courseThumbUrl" class="avatar" />
              <i v-else class="el-icon-plus avatar-uploader-icon"></i>
            </el-upload>

            
          </el-form-item>
        </el-col>

        <el-col :span="8">
          <el-form-item label="开始时间" prop="validStartTime">
            <el-date-picker
              clearable
              v-model="form.validStartTime"
              type="date"
              style="width:100%;"
              value-format="yyyy-MM-dd"
              placeholder="选择课程起始开始时间"
            ></el-date-picker>
          </el-form-item>
        </el-col>
        <el-col :span="8">
          <el-form-item label="结束时间" prop="validEndTime">
            <el-date-picker
              clearable
              style="width:100%;"
              v-model="form.validEndTime"
              type="date"
              value-format="yyyy-MM-dd"
              placeholder="选择课程起始结束时间"
            ></el-date-picker>
          </el-form-item>
        </el-col>

        <!-- <el-col :span="8">
          <el-form-item label="开启考试" prop="hasExam">
            <el-radio-group v-model="form.hasExam">
              <el-radio
                v-for="dict in hasExamOptions"
                :key="dict.dictValue"
                :label="dict.dictValue"
              >{{dict.dictLabel}}</el-radio>
            </el-radio-group>
          </el-form-item>
        </el-col> -->

        <el-col :span="8">
          <el-form-item label="状态" prop="status">
            <el-radio-group v-model="form.status">
              <el-radio
                v-for="dict in statusOptions"
                :key="dict.dictValue"
                :label="dict.dictValue"
              >{{dict.dictLabel}}</el-radio>
            </el-radio-group>
          </el-form-item>
        </el-col>
        <el-col :span="8">
          <el-form-item label="显示排序" prop="orderNum">
            <el-input-number
              v-model="form.orderNum"
              style="width:100%"
              controls-position="right"
              :min="0"
            />
          </el-form-item>
        </el-col>
      </el-row>
      <el-row>
        <span style="font-size: 18px;">高级设置</span>
        <el-divider></el-divider>
        <!-- <el-col :span="8">
          <el-form-item label="付费类型" prop="payType">
            <el-select v-model="form.payType" style="width:100%" placeholder="请选择付费类型">
              <el-option
                v-for="dict in payTypeOptions"
                :key="dict.dictValue"
                :label="dict.dictLabel"
                :value="dict.dictValue"
              ></el-option>
            </el-select>
          </el-form-item>
        </el-col>
        <el-col :span="8">
          <el-form-item label="购买价格" prop="payValue">
            <el-input v-model="form.payValue" placeholder="请输入购买价格" />
          </el-form-item>
        </el-col>
        <el-col :span="8">
          <el-form-item label="会员价" prop="payMemeberValue">
            <el-input v-model="form.payMemeberValue" placeholder="请输入会员购买价格" />
          </el-form-item>
        </el-col>
        <el-col :span="8">
          <el-form-item label="折扣类型" prop="discountType">
            <el-select v-model="form.discountType" style="width:100%" placeholder="请选择折扣类型">
              <el-option
                v-for="dict in discountTypeOptions"
                :key="dict.dictValue"
                :label="dict.dictLabel"
                :value="dict.dictValue"
              ></el-option>
            </el-select>
          </el-form-item>
        </el-col>
        <el-col :span="8">
          <el-form-item label="折扣价格" prop="discountValue">
            <el-input v-model="form.discountValue" placeholder="请输入折扣价格" />
          </el-form-item>
        </el-col> -->
        <el-col :span="24" style="margin-bottom: 30px;">
          <el-form-item label="节目描述" prop="courseDes">
            <Editor v-model="form.courseDes" />
          </el-form-item>
        </el-col>
        <el-col :span="24">
          <el-form-item label="节目内容" style="margin-bottom: 30px;" prop="courseContent">
            <Editor v-model="form.courseContent" />
          </el-form-item>
        </el-col>
      </el-row>
    </el-form>
    <div slot="footer" class="dialog-footer" style="margin-top: 30px;text-align: center;">
      <el-button type="primary" @click="submitForm">确 定</el-button>
      <el-button @click="cancel">取 消</el-button>
    </div>
  </div>
</template>

<style>
.avatar-uploader .el-upload {
  border: 1px dashed #d9d9d9;
  border-radius: 6px;
  cursor: pointer;
  position: relative;
  overflow: hidden;
}
.avatar-uploader .el-upload:hover {
  border-color: #409eff;
}
.avatar-uploader-icon {
  font-size: 28px;
  color: #8c939d;
  width: 156px;
  height: 156px;
  line-height: 156px;
  text-align: center;
}
.avatar {
  width: 156px;
  height: 156px;
  display: block;
}
</style>

<script>


import { listCourse, getCourse, delCourse, addCourse, updateCourse, exportCourse } from "@/api/wechat/course";

import Editor from "@/components/Editor";

import { getToken } from "@/utils/auth";
export default {
  components: {
    Editor,
  },
  data() {
    return {
      // 遮罩层
      uploadImgUrl: null,
      loading: true,
      courseOptions: [],
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 总条数
      total: 0,
      // 维修培训管理表格数据
      maintaincourseList: [],
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      // 课程等级字典
      levelOptions: [],
      // 购买类型 0免费 1付费字典
      payTypeOptions: [],
      // 购买类型 0原价 1限时特价 2会员价字典
      discountTypeOptions: [],
      // 是否有考试字典
      hasExamOptions: [],
      // 课程状态字典
      statusOptions: [],
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        courseTitle: undefined,
        courseTypeId: undefined,
        viewNum: undefined,
        likeNum: undefined,
        courseThumbUrl: undefined,
        courseDes: undefined,
        courseContent: undefined,
        validStartTime: undefined,
        validEndTime: undefined,
        level: undefined,
        payType: undefined,
        payValue: undefined,
        discountType: undefined,
        discountValue: undefined,
        payMemeberValue: undefined,
        courseLength: undefined,
        hasExam: undefined,
        status: undefined,
        orderNum: 1
      },
      // 表单参数
      form: {
        courseId: undefined,
        courseTitle: undefined,
        courseTypeId: undefined,
        viewNum: undefined,
        likeNum: undefined,
        courseThumbUrl: undefined,
        courseDes: undefined,
        courseContent: undefined,
        validStartTime: undefined,
        validEndTime: undefined,
        level: undefined,
        payType: undefined,
        payValue: undefined,
        discountType: undefined,
        discountValue: undefined,
        payMemeberValue: undefined,
        courseLength: undefined,
        hasExam: "0",
        status: "0",
        orderNum: 1,
        delFlag: undefined,
        createBy: undefined,
        createTime: undefined,
        updateBy: undefined,
        updateTime: undefined
      },
      uploadImgUrl: process.env.VUE_APP_BASE_API + "/common/upload", // 上传的图片服务器地址
      headers: {
        Authorization: "Bearer " + getToken()
      },
      // 表单校验
      rules: {
        courseTitle: [
          { required: true, message: "课程标题不能为空", trigger: "blur" }
        ],
        level: [
          { required: true, message: "课程等级不能为空", trigger: "blur" }
        ],
        payType: [
          { required: true, message: "付费类型不能为空", trigger: "blur" }
        ],
        payValue: [
          { required: true, message: "付费价格不能为空", trigger: "blur" }
        ],
        discountType: [
          { required: true, message: "折扣类型不能为空", trigger: "blur" }
        ],
        discountValue: [
          { required: true, message: "折扣价格不能为空", trigger: "blur" }
        ],
        payMemeberValue: [
          { required: true, message: "会员价不能为空", trigger: "blur" }
        ],
        courseLength: [
          { required: true, message: "课程时长不能为空", trigger: "blur" }
        ],
        validStartTime: [
          { required: true, message: "开始时间不能为空", trigger: "blur" }
        ],
        validEndTime: [
          { required: true, message: "结束时间不能为空", trigger: "blur" }
        ],
        courseThumbUrl: [
          { required: true, message: "课程简图不能为空", trigger: "blur" }
        ],
        courseDes: [
          { required: true, message: "课程描述不能为空", trigger: "blur" }
        ],
        courseContent: [
          { required: true, message: "课程内容不能为空", trigger: "blur" }
        ],
        courseTypeId: [
          { required: true, message: "课程类型不能为空", trigger: "blur" }
        ],
        viewNum: [
          { required: true, message: "浏览人数不能为空", trigger: "blur" }
        ],
        likeNum: [
          { required: true, message: "点赞人数不能为空", trigger: "blur" }
        ]
      }
    };
  },
  created() {
    const courseId = this.$route.params && this.$route.params.courseId;
    getCourse(courseId).then(response => {
        this.form = response.data;
      });
    this.getDicts("course_level").then(response => {
      this.levelOptions = response.data;
    });
    this.getDicts("pay_type").then(response => {
      this.payTypeOptions = response.data;
    });
    this.getDicts("discount_type").then(response => {
      this.discountTypeOptions = response.data;
    });
    this.getDicts("has_exam").then(response => {
      this.hasExamOptions = response.data;
    });
    this.getDicts("sys_normal_disable").then(response => {
      this.statusOptions = response.data;
    });
  },
  methods: {
    // 上传预处理
    beforeUpload(file) {
      if (file.type.indexOf("image/") == -1) {
        this.msgError("文件格式错误，请上传图片类型,如：JPG，PNG后缀的文件。");
      } else {
        const reader = new FileReader();
        reader.readAsDataURL(file);
        // reader.onload = () => {
        //   this.options.img = reader.result;
        // };
      }
    },
    handleUploadSuccess(res, file) {
      console.log(res)
      this.form.courseThumbUrl = res.url;
    },
    beforeAvatarUpload(file) {
      const isJPG = file.type === "image/jpeg";
      const isLt2M = file.size / 1024 / 1024 < 2;

      if (!isLt2M) {
        this.$message.error("上传头像图片大小不能超过 2MB!");
      }
      return isJPG && isLt2M;
    },
    /** 查询菜单下拉树结构 */
    getTreeselect() {
      treeselect().then(response => {
        this.courseOptions = [];
        const courseType = { id: 0, label: "主类目", children: [] };
        courseType.children = response.data;
        this.courseOptions.push(courseType);
      });
    },
    // 课程等级字典翻译
    levelFormat(row, column) {
      return this.selectDictLabel(this.levelOptions, row.level);
    },
    // 购买类型 0免费 1付费字典翻译
    payTypeFormat(row, column) {
      return this.selectDictLabel(this.payTypeOptions, row.payType);
    },
    // 购买类型 0原价 1限时特价 2会员价字典翻译
    discountTypeFormat(row, column) {
      return this.selectDictLabel(this.discountTypeOptions, row.discountType);
    },
    // 是否有考试字典翻译
    hasExamFormat(row, column) {
      return this.selectDictLabel(this.hasExamOptions, row.hasExam);
    },
    // 课程状态字典翻译
    statusFormat(row, column) {
      return this.selectDictLabel(this.statusOptions, row.status);
    },
    // 取消按钮
    cancel() {
      console.log("cancel");
      this.$store.dispatch("tagsView/delView", this.$route);
      this.toLastView();
    },
    toLastView() {
      const latestView = this.$store.state.tagsView.visitedViews.slice(-1)[0];
      console.log(latestView.path);
      if (latestView) {
        this.$router.push(latestView);
      } else {
        // now the default is to redirect to the home page if there is no tags-view,
        // you can adjust it according to your needs.
        this.$router.push("/");
      }
    },
    /** 提交按钮 */
    submitForm: function() {
      this.$refs["form"].validate(valid => {
        if (valid) {
          if (this.form.courseId != undefined) {
            updateCourse(this.form).then(response => {
              if (response.code === 200) {
                this.msgSuccess("修改成功");
                this.$store.dispatch("tagsView/delView", this.$route);
                this.toLastView();
              } else {
                this.msgError(response.msg);
              }
            });
          } else {
            addMaintaincourse(this.form).then(response => {
              if (response.code === 200) {
                this.msgSuccess("新增成功");
                this.$store.dispatch("tagsView/delView", this.$route);
                this.toLastView();
              } else {
                this.msgError(response.msg);
              }
            });
          }
        }
      });
    },
  }
};
</script>